<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>无标题文档</title>
    <link href="../../css/style.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="../../js/jquery.js"></script>
    <script type="text/javascript" src="../../js/axios.js"></script>
    <script type="text/javascript" src="../../js/api.js"></script>
    <script type="text/javascript" src="../../layui/layui.js"></script>
    <script type="text/javascript" src="../../laydate/laydate.js"></script>
    <link href="../../layui/css/layui.css" rel="stylesheet" type="text/css"/>
    <link href="../../laydate/need/laydate.css" rel="stylesheet" type="text/css"/>
</head>

<body>
<div class="place"><span>位置：</span>
    <ul class="placeul">
        <li>采购管理</li>
        <li>采购单管理</li>
        <li>修改</li>
    </ul>
</div>
<div class="formbody">
    <div class="formtitle"><span>采购单信息</span></div>
    <form id="purchase">
        <ul class="forminfo">
            <li>
                <label>采购单编号</label>
                <input name="purchaseId" type="text" value="CG201711180001" readonly="readonly" class="roinput"/>
                <i>自动生成不能编辑</i>
            </li>
            <li>
                <label>采购时间</label>
                <input name="purchaseTime" type="text" value="2017-11-18 15:36:10" readonly="readonly" class="roinput"/>
                <i>不能编辑</i>
            </li>
            <li>
                <label>创建人</label>
                <input name="creatId" type="text" value="马云" readonly="readonly" class="roinput"/>
                <i>不能编辑</i>
            </li>
            <li>
                <label>审核状态</label>
                <input type="text" id="checkStatus" value="未审核" readonly="readonly" class="roinput"/>
                <input name="checkStatus" type="hidden" value="1"/>
                <i>初始状态，不能编辑</i>
            </li>
            <li>
                <label>总金额</label>
                <input name="totalMoney" id="money" type="text" value="9876582" readonly="readonly" class="roinput"/>
                <i>自动运算，不能编辑</i>
            </li>
            <li>
                <input type="button" id="addbutton" value="新增" class="smallbtn"/>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <input type="button" id="delbutton" value="删除" class="smallbtn"/>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <input type="button" id="submitbutton" value="保存" class="smallbtn"/>
                &nbsp;&nbsp;&nbsp;&nbsp;<!--onclick="window.location.href='purchaseList.html'"-->
                <input type="button" id="backbutton" value="返回" class="smallbtn"/>
            </li>
        </ul>
    </form>
    <table class="tablelist">
        <thead>
        <tr>
            <th><input type="checkbox" id="checkAll">全选</th>
            <th>序号</th>
            <th>品牌</th>
            <th>类型</th>
            <th>型号</th>
            <th>厂商</th>
            <th>数量</th>
            <th>单位</th>
            <th>单价</th>
            <th>金额</th>
        </tr>
        </thead>
        <tbody id="tbody">
        <!--<tr>
        <td>1</td>
        <td>
            <select>
              <option>请选择</option>
              <option selected="selected">联想</option>
              <option>海尔</option>
              <option>小米</option>
          </select>
        </td>
        <td>
            <select>
              <option>请选择</option>
              <option selected="selected">笔记本电脑</option>
              <option>台式电脑</option>
              <option>手机</option>
          </select>
        </td>
        <td>
            <select>
              <option>请选择</option>
              <option>X260</option>
              <option>E470</option>
              <option selected="selected">T470</option>
          </select>
        </td>
        <td>
            <select>
              <option>请选择</option>
              <option selected="selected">北京联想科技股份有限公司</option>
              <option>北京京东商贸股份有限公司</option>
          </select>
        </td>
        <td><input type="text" value="10" /></td>
        <td>台</td>
        <td><input type="text" value="9998" /></td>
        <td><input type="text" value="99980" /></td>
      </tr>
      <tr>
        <td>2</td>
        <td>
            <select>
              <option>请选择</option>
              <option selected="selected">联想</option>
              <option>海尔</option>
              <option>小米</option>
          </select>
        </td>
        <td>
            <select>
              <option>请选择</option>
              <option selected="selected">笔记本电脑</option>
              <option>台式电脑</option>
              <option>手机</option>
          </select>
        </td>
        <td>
            <select>
              <option>请选择</option>
              <option selected="selected">X260</option>
              <option>E470</option>
              <option>T470</option>
          </select>
        </td>
        <td>
            <select>
              <option>请选择</option>
              <option selected="selected">北京联想科技股份有限公司</option>
              <option>北京京东商贸股份有限公司</option>
          </select>
        </td>
        <td><input type="text" value="5" /></td>
        <td>台</td>
        <td><input type="text" value="5500" /></td>
        <td><input type="text" value="27500" /></td>
      </tr>-->
        </tbody>
    </table>
</div>
<script type="text/javascript">
    $('.tablelist tbody tr:odd').addClass('odd');

    let brand = '';
    let autoId = 0;
    let productList = []; //用于存放商品信息
    $(function () {
        //加载品牌数据--将其存在一个全局变量里
        axiosJson('get', '/purchase/brand', null, null).then((res) => {
            brand = res.data.resultData;
        })
        loadData()

    })
    let parameter1 = getParameter('pageNum');
    let parameter3 = getParameter('condition');
    //点击返回，回退到点击修改前的页面
    $('#backbutton').click(() => {
        window.location.href = 'purchaseList.html?pageNum=' + parameter1 + '&condition=' + parameter3
    })

    function loadData() {
        let parameter = getParameter("purchaseId");
        axiosJson('get', '/purchase/detail', null, {purchaseId: parameter}).then((res) => {
            let data = res.data.resultData;
            var arr = ['未审核', '审核中', '审核通过', '审核未通过'];
            let status = data.purchase.checkStatus;
            for (let i = 0; i <arr.length ; i++) {
                if (status == (i + 1)) status = arr[i]
            }
            $("[name='purchaseId']").val(data.purchase.purchaseId)
            $("[name='purchaseTime']").val(data.purchase.purchaseTime)
            console.log(data.purchase.creator)
            $("[name='creatId']").val(data.purchase.creator.uName)
            $('#checkStatus').val(status)
            $("[name='totalMoney']").val(data.purchase.totalMoney)
            //拼写表格(商品信息)
            writeTable(data.purchaseData)
        })
    }


    //拼写表格数据---初始化
    function writeOriginal(data, autoId) {
        //回显数据的id
        let bd = data.brandId;
        let td = data.typeId;
        let pd = data.productId;
        let fd = data.firmId;
        //类型、商品信息、厂商信息所在的对象
        let code = data.data;
        //品牌下拉框填充数据
        let brandName = ''
        let typeName = ''
        let productName = ''
        let firmName = ''
        for (let i = 0; i < brand.length; i++) {
            let bid = brand[i].brandId
            brandName += '<option  value="' + bid + '"  ' + (bid == bd ? 'selected' : '') + ' >' + brand[i].brandName + '</options>'
        }
        let tList = code[0];
        let pList = code[1];
        let fList = code[2];
        for (let i = 0; i < tList.length; i++) {
            typeName += '<option  value="' + tList[i].typeId + '"  ' + (tList[i].typeId == td ? 'selected' : '') + ' >' + tList[i].typeName + '</options>'
        }

        for (let i = 0; i < pList.length; i++) {
            productName += '<option  value="' + pList[i].productId + '"  ' + (pList[i].productId == pd ? 'selected' : '') + ' >' + pList[i].productModel + '</options>'
        }
        for (let i = 0; i < fList.length; i++) {
            firmName += '<option  value="' + fList[i].firmId + '"  ' + (fList[i].firmId == fd ? 'selected' : '') + ' >' + fList[i].firmName + '</options>'
        }

        let str =
            '<tr name="details" id="' + autoId + '" style="height: 30px">\n' +
            '            <td><input name="check" type="checkbox"></td>' +
            '            <td id="xh">' + autoId + '</td>\n' +
            '            <td>\n' +
            '                <select name="brandId" id="' + autoId + '-1">\n' +
            '                    <option value="0">--请选择--</option>\n' + brandName +
            '                </select>\n' +
            '            </td>\n' +
            '            <td>\n' +
            '                <select name="typeId" id="' + autoId + '-2">\n' +
            '                    <option value="0">--请选择--</option>\n' + typeName +
            '                </select>\n' +
            '            </td>\n' +
            '            <td>\n' +
            '                <select name="productModel" id="' + autoId + '-3">\n' +
            '                    <option value="0">--请选择--</option>\n' + productName +
            '                </select>\n' +
            '            </td>\n' +
            '            <td>\n' +
            '                <select name="firmId" id="' + autoId + '-4">\n' +
            '                    <option value="0">--请选择--</option>\n' + firmName +
            '                </select>\n' +
            '            </td>\n' +
            '            <td><input name="count" id="' + autoId + '-5"  value="' + data.count + '" type="number" min="0"/></td>\n' +
            '            <td><input name="productUnit" id="' + autoId + '-6" value="' + data.productUnit + '" type="text"/></td>\n' +
            '            <td><input name="purchasePrice" id="' + autoId + '-7" value="' + data.purchasePrice + '" type="text"/></td>\n' +
            '            <td><input name="totalMoney" id="' + autoId + '-8" value="' + data.totalMoney + '" class="price" type="text"/></td>\n' +
            '            <td><input name="productId" id="' + autoId + '-9"  value="' + data.productId + '"  type="hidden"/></td>\n' +
            '        </tr>+'

        return str;
    }

    //拼写表格数据---新增
    function writeTr(autoId) {
        //品牌下拉框填充数据
        let brandName = ''
        for (let i = 0; i < brand.length; i++) {
            brandName += '<option value="' + brand[i].brandId + '">' + brand[i].brandName + '</option>'
        }
        let str =
            '<tr name="details" id="' + autoId + '" style="height: 30px">\n' +
            '            <td><input name="check" type="checkbox"></td>' +
            '            <td id="xh">' + autoId + '</td>\n' +
            '            <td>\n' +
            '                <select name="brandId" id="' + autoId + '-1">\n' +
            '                    <option value="0">--请选择--</option>\n' + brandName +
            '                </select>\n' +
            '            </td>\n' +
            '            <td>\n' +
            '                <select name="typeId" id="' + autoId + '-2">\n' +
            '                    <option value="0">--请选择--</option>\n' +
            '                </select>\n' +
            '            </td>\n' +
            '            <td>\n' +
            '                <select name="productModel" id="' + autoId + '-3">\n' +
            '                    <option value="0">--请选择--</option>\n' +
            '                </select>\n' +
            '            </td>\n' +
            '            <td>\n' +
            '                <select name="firmId" id="' + autoId + '-4">\n' +
            '                    <option value="0">--请选择--</option>\n' +
            '                </select>\n' +
            '            </td>\n' +
            '            <td><input name="count" id="' + autoId + '-5"  value="" type="number" min="0"/></td>\n' +
            '            <td><input name="productUnit" id="' + autoId + '-6" type="text"/></td>\n' +
            '            <td><input name="purchasePrice" id="' + autoId + '-7" type="text"/></td>\n' +
            '            <td><input name="totalMoney" id="' + autoId + '-8" class="price" type="text"/></td>\n' +
            '            <td><input name="productId" id="' + autoId + '-9"  value="" type="hidden"/></td>\n' +
            '        </tr>+'

        return str;
    }

    //写数据
    function writeTable(data) {
        //拼写表格数据
        let trOriginal = ''
        for (let i = 0; i < data.length; i++) {
            // trOriginal +=writeOriginal(data[i],i+1)
            $('#tbody').append(writeOriginal(data[i], i + 1))
            operation(i + 1)
            loadProduct(data[i].typeId, (i + 1) + "-3", data[i].productModel)
        }
        autoId = data.length;
        // $('#tbody').html(trOriginal)
        selectAll();
        //新增一行商品
        $('#addbutton').click(() => {
            autoId++;//id生成自增
            $('#tbody').append(writeTr(autoId))

            let xh = document.querySelectorAll("#xh");
            for (let i = 0; i < xh.length; i++) {
                xh[i].innerHTML = (i + 1)
            }
            operation(autoId);
            selectAll();
        })

        //删除选中行商品信息
        $('#delbutton').click(() => {
            //遍历所有 name=check 的复选框
            $("[name='check']").each(function () {
                //若被选中，则删除
                if ($(this).is(":checked")) {
                    $(this).parent().parent().remove()
                    totalMoney()
                }
            })
            let xh = document.querySelectorAll("#xh");
            for (let i = 0; i < xh.length; i++) {
                xh[i].innerHTML = (i + 1)
            }
        })
    }

    //当改变前一个input标签时，后面的input 标签会清空
    function cleanInput(autoId) {
        $('#' + autoId + '-5').val('')
        $('#' + autoId + '-6').val('')
        $('#' + autoId + '-7').val('')
        $('#' + autoId + '-8').val('')
        $('#' + autoId + '-9').val('')
    }

    //表格里的下拉框操作
    function operation(autoId) {
        //品牌框发生改变后、类型下拉框就要出现对应的类型
        $('#' + autoId + '-1').change(function () {
            let bid = $('#' + autoId + '-1').val()
            loadType(bid, autoId + '-2')
            $('#' + autoId + '-2').html('<option>--请选择--</option>')
            $('#' + autoId + '-3').html('<option>--请选择--</option>')
            $('#' + autoId + '-4').html('<option>--请选择--</option>')
            cleanInput(autoId);
        })

        //类型框，发生改变后，型号下拉框就要发生改变
        $('#' + autoId + '-2').change(function () {
            let tid = $('#' + autoId + '-2').val()
            loadProduct(tid, autoId + '-3', 0)
            $('#' + autoId + '-3').html('<option>--请选择--</option>')
            $('#' + autoId + '-4').html('<option>--请选择--</option>')
            cleanInput(autoId);
        })

        //型号框确定后、由类型、型号可以缩小厂商
        $('#' + autoId + '-3').change(function () {
            let tid = $('#' + autoId + '-2').val()
            let model = $('#' + autoId + '-3').val()
            loadFirm(tid, model, autoId + '-4')
            $('#' + autoId + '-4').html('<option>--请选择--</option>')
            cleanInput(autoId);
        })

        //品牌、类型、型号、厂商确定后，就能确定商品id;去全局变量productList匹配相同的信息
        $('#' + autoId + '-4').change(function () {
            cleanInput(autoId);
            let fid = $('#' + autoId + '-4').val();
            for (let pl in productList[autoId]) {
                if (productList[autoId][pl].firmId == fid) {
                    // console.log(productList[pl].firmId)

                    $('#' + autoId + '-5').val(1)
                    $('#' + autoId + '-6').val(productList[autoId][pl].productUnit)
                    $('#' + autoId + '-7').val(productList[autoId][pl].productPrice)
                    $('#' + autoId + '-8').val(productList[autoId][pl].productPrice)
                    $('#' + autoId + '-9').val(productList[autoId][pl].productId)
                    totalMoney()
                }
            }
        })

        //当数量发生改变时，计算出总金额
        $('#' + autoId + '-5')[0].oninput = function () {
            let price = $('#' + autoId + '-7').val();
            let number = $('#' + autoId + '-5').val();
            let money = price * number;
            $('#' + autoId + '-8').val(money)
            totalMoney()
        }
    }

    //计算采购单的总金额
    function totalMoney() {
        let price = $('.price');
        sum = 0;
        for (let i = 0; i < price.length; i++) {
            sum += Number(price[i].value);
        }
        $('#money').val(sum)
    }

    //保存 并返回到管理列表视图(退出添加页面)
    $('#submitbutton').click(() => {
        //获取行数
        let tr = $("[name='details'] ")
        let arr = [];
        // console.log(tr.length)
        //获取表格里的采购单信息
        for (let i = 0; i < tr.length; i++) {
            let obj = {};
            let id = $(tr[i]).attr("id");
            for (let j = 5; j <= 9; j++) {
                let $td = $(`#${id}-${j}`);
                obj[$td.attr("name")] = $td.val();
            }
            arr.push(obj)
        }
        let conn = $('#purchase').serializeArray();
        if (verification()) {
            axiosBody('/purchase/updateDetail', conn, arr).then((res) => {
                alert(res.data.msg)
                window.location.href = 'purchaseList.html';
            })
        } else {
            alert('请完善需采购的商品信息！')
        }
    })

    //商品信息(表格)非空验证、因为每行是由前往后填写的所以只需判断最后一个即厂商、数量非空就好了
    function verification() {
        let tr = $("[name='details'] ")
        let flag = true;
        if (tr.length == 0) {
            flag = false
            alert("请添加商品信息")
        } else {
            for (let i = 0; i < tr.length; i++) {
                let fid = $(tr[i]).find("[name='firmId']").val();
                let count = $(tr[i]).find("[name='count']").val();

                if (fid == 0 || count == 0) {
                    flag = false;
                }
            }
        }
        return flag;
    }

    //通过brandId 查询类型
    function loadType(brandId, tid) {
        axiosJson('get', '/purchase/type', null, {brandId: brandId}).then((res) => {
            let type = res.data.resultData;
            let typeName = '<option value="0">--请选择--</option>'
            for (let i = 0; i < type.length; i++) {
                typeName += '<option value="' + type[i].typeId + '">' + type[i].typeName + '</option>'
            }
            //填充到下拉框
            $('#' + tid).html(typeName)
        })
    }

    //通过typeId 查询商品信息(型号、厂商id、单价)
    function loadProduct(typeId, pid, def) {
        axiosJson('get', '/purchase/product', null, {typeId: typeId}).then((res) => {
            productList[pid.split("-")[0]] = res.data.resultData; //存进全局变量
            let pMName = '<option>--请选择--</option>'
            let product = res.data.resultData;
            for (let pm in product) {
                pMName += '<option >' + product[pm].productModel + '</option>'
            }
            //填充到下拉框
            $('#' + pid).html(pMName)
            $('#' + pid).val(def)
        })
    }

    //通过typeId、productModel 查询 厂商
    function loadFirm(tid, model, fid) {
        axiosJson('get', '/purchase/firm', null, {typeId: tid, productModel: model}).then((res) => {
            let firmName = '<option value="0">--请选择--</option>'
            let firm = res.data.resultData;
            for (let fm in firm) {
                firmName += '<option value="' + firm[fm].firmId + '">' + firm[fm].firmName + '</option>'
            }
            //填充到对应的字段
            $('#' + fid).html(firmName)
        })
    }
</script>
</body>
</html>
